package com.lafeng.journey.httputils;

import android.util.Log;

import com.lafeng.journey.basisapp.App;
import com.lafeng.journey.utils.APPNetWork;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by zhiguo on 2016/7/11.
 * 封装了一个RX系列网络下载的类    这边主要是做一些配置和初始化
 */
public class HttpRetrofit{

    private static OkHttpClient okHttpClient;

    public HttpRetrofit(){
        okHttpClient  = setOkHttpClient();
    }

    /**
     * 设置调用OkHttpClient
     */
    private OkHttpClient setOkHttpClient(){
        return new OkHttpClient().newBuilder()
                .addInterceptor(getHttpLoggingInterceptor())
                //缓存这两个都要设置才行
                .addNetworkInterceptor(getNetWorkInterceptor())
                .addInterceptor(getInterceptor())
                .cache(new Cache(App.getIntense().getCacheDir(), 10 * 1024 * 1024))
                .retryOnConnectionFailure(true) //失败重连
                .readTimeout(25, TimeUnit.SECONDS)
                .connectTimeout(25, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 初始化retrofit
     * @return
     */
    public Retrofit getRetrofit(){
        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl("http://weatherapi.market.xiaomi.com/")  //服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    /**
     * 封装调用   主要是设置订阅的线程转换
     * @param observable
     * @param subscriber
     * @param <T>
     */
    public <T> void httpSubscribe(Observable<T> observable, Subscriber<T> subscriber){
        observable
                .map(new Func1<T, T>() {
                    @Override
                    public T call(T t) {
                        //在这里进行转化, 进行json外层部分的判断并返回

                        return t;
                    }
                })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    /**
     * 关联接口类
     * @return
     */
    public  ApiService getApiService(){
        return getRetrofit().create(ApiService.class);
    }

    /**
     * 设置连接器  设置缓存
     */
    public Interceptor getNetWorkInterceptor (){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                if (APPNetWork.isNetworkConnected(App.getIntense())) {
                    int maxAge = 0 * 60;
                    // 有网络时 设置缓存超时时间0个小时
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")
                            // 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    // 无网络时，设置超时为1周
                    int maxStale = 60 * 60 * 24 * 7;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
    }

    /**
     * 设置返回的  Interceptor  拦截判断网络   没网读取缓存
     */
    public Interceptor getInterceptor(){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!APPNetWork.isNetworkConnected(App.getIntense())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                return chain.proceed(request);
            }
        };
    }

    /**
     * 日志打印
     * @return
     */
    private  HttpLoggingInterceptor  getHttpLoggingInterceptor(){
        return  new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("RxAndroid--", message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);
    }
}
